package com.finger.eduservice.controller.front;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.finger.commonutils.JwtUtils;
import com.finger.commonutils.R;
import com.finger.eduservice.client.UcenterClient;
import com.finger.eduservice.entity.EduComment;
import com.finger.eduservice.exception.GuliException;
import com.finger.eduservice.service.EduCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.ref.ReferenceQueue;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author finger
 * @since 2022-01-26
 */
@RestController
@RequestMapping("/eduservice/comment")
@CrossOrigin
public class EduCommentController {

    @Autowired
    private EduCommentService eduCommentService;

    @Autowired
    private UcenterClient ucenterClient;

    @PostMapping("/addComment")
    public R addComment(@RequestBody EduComment eduComment,
                        HttpServletRequest request){

        String id = JwtUtils.getMemberIdByJwtToken(request);
        R memberInfo = ucenterClient.getMemberInfoComment(id);

        if(!memberInfo.getSuccess()){
            throw new GuliException(20001,"获取用户信息失败");
        }
        Map<String, Object> data = memberInfo.getData();

        try {
            eduComment.setNickname((String) data.get("nickname"));
            eduComment.setMemberId((String) data.get("memberId"));
            eduComment.setAvatar((String) data.get("avatar"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"用户信息获取失败");
        }

        boolean save = eduCommentService.save(eduComment);

        if(!save){
            throw new GuliException(20001,"保存失败");
        }

        return R.ok();
    }

    @GetMapping("/getCommentPage/{page}/{size}/{id}")
    public R getCommentPage(@PathVariable long page,
                            @PathVariable long size,
                            @PathVariable String id){

        Page<EduComment> eduCommentPage = new Page<>(page, size);

        Map<String,Object> map = eduCommentService.pageComment(eduCommentPage,id);

        return R.ok().data("data",map);
    }
}

